﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using CommonHelper;

namespace CommonLibrary
{
    /// <summary>
    /// 临时数据加密处理类
    /// </summary>
    public static class CryptHelper
    {
        private static Aes aes;

        static CryptHelper()
        {
            aes = Aes.Create();
            aes.GenerateIV();
            aes.GenerateKey();
        }

        /// <summary>
        /// 临时加密
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string Encrypt<T>(T content)
        {            
            using (var encrypt = aes.CreateEncryptor())
            {
                var buffer = Encoding.UTF8.GetBytes(content.ToString());
                return Convert.ToBase64String(encrypt.TransformFinalBlock(buffer, 0, buffer.Length));
            }
        }

        /// <summary>
        /// 对临时加密的秘密进行解密
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string Decrypt(string content)
        {            
            using (var decrypt = aes.CreateDecryptor())
            {
                var buffer = Convert.FromBase64String(content.Replace(' ', '+'));
                return Encoding.UTF8.GetString(decrypt.TransformFinalBlock(buffer, 0, buffer.Length));
            }
        }

        /// <summary>
        /// 对临时加密的秘密进行解密
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static int DecryptToInt32(string content)
        {
            return Decrypt(content).ToInt32();
        }        
    }
}
